package org.example.apifallback;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.FilenameIndex;
import com.intellij.psi.search.GlobalSearchScope;
import org.example.apifallback.notice.CommentNotice;
import org.jetbrains.annotations.NotNull;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;
import  com.intellij.openapi.command.WriteCommandAction;
/**
 * @author zengxiaoyu
 * @date 2025/8/4 18:00
 */
public class SetAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        assert editor != null;
        SelectionModel selectionModel = editor.getSelectionModel();
        String selectedText = selectionModel.getSelectedText();
        if (selectedText != null) {
            // 执行你想要的操作，例如替换选中的文本
            // 1. 解析选择的文本中的类名
            // 例如，从选中的文本中提取类名  xxx  = new abc(); xxxxx
            // 提取 abc这类字符 作为类名
            Pattern pattern = Pattern.compile("new (\\w+)");
            java.util.regex.Matcher matcher = pattern.matcher(selectedText);
            String className = "";
            if (matcher.find()) {
                className = matcher.group(1);
            }
            // 在 idea的vfs中查找名称为className的类文件
            @NotNull PsiFile @NotNull [] files = FilenameIndex.getFilesByName(project, className + ".java", GlobalSearchScope.allScope(project));
            if (files.length == 0) {
                CommentNotice.show("Class " + className + " not found", project);
                return;
            }
            @NotNull PsiFile classFile = files[0];
            if (!(classFile instanceof PsiJavaFile)) {
                CommentNotice.show("Selected file is not a Java file", project);
                return;
            }
            PsiClass[] classes = ((PsiJavaFile) classFile).getClasses();
            if (classes.length == 0) {
                CommentNotice.show("No class found in file", project);
                return;
            }
            PsiClass targetClass = classes[0];
            //2. 根据类及父类的 反射生成所有字段的set方法 排除object类的字段
            Set<String> fieldNames = generateFieldNames(targetClass);
            if (fieldNames.isEmpty()) {
                CommentNotice.show("No fields found in class:" + targetClass.getName(), project);
            } else {
                // 生成set方法
                StringBuilder sb = new StringBuilder().append("\n");
                for (String fieldName : fieldNames) {
                    sb.append("this.set").append(fieldName).append("(null);").append("\n");
                }

                Document document = editor.getDocument();
                int offset = editor.getSelectionModel().getSelectionEnd();
                WriteCommandAction.runWriteCommandAction(project, () -> {
                    try {
                        document.insertString(offset, sb.toString());
                    } catch (Exception ex) {
                        CommentNotice.show("Failed to generate set methods: " + ex.getMessage(), project);
                    }
                });
                // 替换选中的文本
               // editor.getDocument().replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), sb.toString());
                CommentNotice.show("set方法生成成功", project);
            }


        } else {
            // 弹框 提示  没有选中文本
            //System.out.println("Please select some text first.");
            CommentNotice.show("Please select some text first.", project);
        }
    }

    public static Set<String> generateFieldNames(PsiClass clazz) {
        // 获取所有字段
        PsiField[] fields = clazz.getAllFields();
        Set<String> fileNames = new LinkedHashSet<>();
        // 遍历字段生成set方法
        for (PsiField field : fields) {
            String fieldName = field.getName();
            String capitalizedName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            fileNames.add(capitalizedName);
        }
        // 获取父类的所有字段
        PsiClass superClass = clazz.getSuperClass();
        if (superClass != null && !superClass.getQualifiedName().equals("java.lang.Object")) {
            Set<String> strings = generateFieldNames(superClass);
            if (!strings.isEmpty()) {
                fileNames.addAll(strings);
            }
        }
        return fileNames;

    }
}
